using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.AliPay;

/// <summary>
/// 支付宝服务商配置
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class AliProviderService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<AliPayProvider> _rep;

	public AliProviderService(SqlSugarRepository<AliPayProvider> rep)
	{
		_rep = rep;
	}

	/// <summary>
	/// 保存支付宝配置
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/alipay/editalipay")]
	public async Task EditAliPay(AliPayInput input)
	{
		AliPayProvider entity = input.Adapt<AliPayProvider>();
		if (input.Id.HasValue)
		{
			AliPayProvider model = await _rep.GetFirstAsync((AliPayProvider u) => (long?)u.Id == input.Id);
			if (model == null)
			{
				throw Oops.Bah("当前数据不存在");
			}
			if (entity.AppId != null && !entity.AppId.Contains("*"))
			{
				model.AppId = entity.AppId;
			}
			if (entity.AppPrivateKey != null && !entity.AppPrivateKey.Contains("*"))
			{
				model.AppPrivateKey = entity.AppPrivateKey;
			}
			if (entity.AlipayPublicKey != null && !entity.AlipayPublicKey.Contains("*"))
			{
				model.AlipayPublicKey = entity.AlipayPublicKey;
			}
			if (entity.EncryptKey != null && !entity.EncryptKey.Contains("*"))
			{
				model.EncryptKey = entity.EncryptKey;
			}
			model.Remark = entity.Remark;
			model.AliPayPayUrl = entity.AliPayPayUrl;
			await _rep.UpdateAsync(model);
		}
		else
		{
			await _rep.InsertOrUpdateAsync(entity);
		}
	}

	/// <summary>
	/// 查询支付宝配置
	/// </summary>
	/// <returns></returns>
	[HttpGet("/alipay/list/")]
	public async Task<AliPayProvider> GetAliPay()
	{
		AliPayProvider model = await _rep.GetFirstAsync((AliPayProvider u) => true);
		string pattern = "(?<=[\\S]{4})\\S(?=[\\S]{4})";
		Regex rgx = new Regex(pattern);
		if (model != null)
		{
			if (model.AppId != null && model.AppId.Length > 8)
			{
				model.AppId = rgx.Replace(model.AppId, "*");
			}
			if (model.AlipayPublicKey != null && model.AlipayPublicKey.Length > 8)
			{
				model.AlipayPublicKey = rgx.Replace(model.AlipayPublicKey, "*");
			}
			if (model.AppPrivateKey != null && model.AppPrivateKey.Length > 8)
			{
				model.AppPrivateKey = rgx.Replace(model.AppPrivateKey, "*");
			}
			if (model.EncryptKey != null && model.EncryptKey.Length > 8)
			{
				model.EncryptKey = rgx.Replace(model.EncryptKey, "*");
			}
		}
		return model;
	}

	/// <summary>
	/// 删除配置
	/// </summary>
	/// <returns></returns>
	[HttpPost("/alipay/delete")]
	public async Task Deleteali()
	{
		await _rep.DeleteAsync((AliPayProvider d) => true);
	}
}
